// pages/invoicingApplication/invoicingApplication.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        collection: [],
        imgList: [],
        contract: [],
        picList: [],
        email: '',
        invoice_ext: [],
        company_id: '',
        company: {},
        address: {},
        address_id: '',
        invoice_ext_index: '',
        show: false,
        picSrcArr: [],
        imgSrcArr: [],
        isLoadData: true,
        type: ''
    },

    selectCol(e) {
        let {
            index
        } = e.currentTarget.dataset;
        this.setData({
            invoice_ext_index: index
        })
        let col = JSON.stringify(this.data.invoice_ext[index]);
        wx.navigateTo({
            url: `/pages/addTr/addTr?col=${col}&index=${index}`
        })
    },

    naturalApply() {
        // if (this.data.collection && this.data.collection.length <= 0) {
        //     return wx.$Toast("请上传收款依据");
        // }


        if (this.data.invoice_ext && this.data.invoice_ext.length <= 0) {
            return wx.$Toast("请选择服务类目");
        }
        if (this.data.contract && this.data.contract.length <= 0) {
            return wx.$Toast("请上传服务合同");
        }
        if (!this.data.company_id) {
            return wx.$Toast("请选择企业信息");
        }
        if (!this.data.address_id) {
            return wx.$Toast("请选择收件信息");
        }
        if (!this.data.email) {
            return wx.$Toast("请输入电子邮箱");
        }
        let that = this;
        let {
            invoice_ext,
            collection,
            contract,
            company_id,
            address_id,
            email
        } = that.data;
        let data = {
            invoice_ext,
            collection,
            contract,
            company_id,
            address_id,
            email
        }
        wx.$api.naturalApply(data).then(res => {
            let {
                code,
                msg
            } = res.data;
            if (code == 200) {
                let data = JSON.stringify(res.data.data);
                wx.navigateTo({
                    url: '/pages/billingConfirmation/billingConfirmation?data=' + data,
                })
            } else {
                wx.$Toast(msg)
            }
        }).catch(ret => {
            wx.$Toast(ret.msg || "服务繁忙")
        })
    },
    addCol(e) {
        this.setData({
            invoice_ext_index: ''
        })
        wx.navigateTo({
            url: '/pages/addTr/addTr',
        })

    },
    emailBlur(e) {
        console.log(e);
        let {
            value
        } = e.detail;
        if (value && !wx.$isEmail(value)) {
            wx.$Toast('邮箱格式不对！')
        }
        this.setData({
            email: value
        })
    },
    changeExt(data) {
        let {
            invoice_ext,
            invoice_ext_index,
        } = this.data;
        if (parseInt(invoice_ext_index) >= 0) {
            if (data && data.length > 0) {
                invoice_ext.splice(invoice_ext_index, 1, data[0])
            } else {
                invoice_ext.splice(invoice_ext_index, 1)
            }
        } else {
            invoice_ext.push(data[0])
        }
        console.log(invoice_ext)
        this.setData({
            invoice_ext: invoice_ext
        })

    },
    changeAddressInfo(params) {
        if (params) {
            this.setData({
                address: params.address,
                address_id: params.address.natural_address_id
            })
        }
    },
    changeCompanyInfo(params) {
        console.log(params)
        if (params) {
            this.setData({
                company: params.company,
                company_id: params.company.natural_company_id
            })
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(options)

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },
    getData() {
        wx.$api.defaultInfo().then(res => {
            let {
                code,
                data
            } = res.data;
            console.log(data)
            let {
                defaultAddress,
                defaultCompany,
                email
            } = data
            if (code == 200) {
                this.setData({
                    company: defaultCompany || {},
                    company_id: defaultCompany ? defaultCompany.natural_company_id : '',
                    address: defaultAddress || {},
                    address_id: defaultAddress ? defaultAddress.natural_address_id : '',
                    email: email || ''
                })
            }
        }).catch(ret => {
            wx.$Toast(ret.msg || "服务繁忙")
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: async function (options) {
        if (this.data.isLoadData) {
            this.getData();
        }
    },
    toEdit(e) {
        let {
            type
        } = e.currentTarget.dataset;
        if (type == 0) {
            wx.navigateTo({
                url: '/pages/companyInfo/companyInfo',
            })
        }
        if (type == 1) {
            wx.navigateTo({
                url: '/pages/mailAddress/mailAddress'

            })
        }
        if (type == 2) {
            wx.navigateTo({
                url: '/pages/mailAddress/mailAddress'
            })
        }

    },

    previewImage(e) {
        let {
            index,
            type
        } = e.currentTarget.dataset, that = this, previewImg;
        type == 0 ? previewImg = this.data.imgSrcArr : previewImg = that.data.picSrcArr;
        console.log(type, previewImg)
        wx.previewImage({
            current: previewImg[index],
            urls: previewImg,
            success: (res) => {
                console.log(res)
            },
            fail: (res) => {
                console.log(res)
            },
            complete: (res) => {
                console.log(res)
            },
        })
    },
    identity(type) {
        let self = this;
        wx.chooseImage({
            count: 9,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],
            success(res) {
                const tempFilePaths = res.tempFilePaths;
                console.log(res, tempFilePaths, '返回参数图片');
                if (type == 0) {
                    let num = tempFilePaths.length + self.data.imgList.length;
                    if (num > 5) {
                        wx.$Toast("最多上传5张照片");
                        return
                    }
                }
                if (type == 1) {
                    let num = tempFilePaths.length + self.data.picList.length;
                    if (num > 20) {
                        wx.$Toast("最多上传20张照片");
                        return
                    }
                }
                for (let i = 0; i < tempFilePaths.length; i++) {
                    self.upimg(tempFilePaths[i], type, self)
                }

            }
        })
    },

    addImg(e) {
        let {
            type
        } = e.currentTarget.dataset, that = this;
        if (type == 0 && that.data.imgList.length > 4) {
            wx.$Toast("最多上传5张照片");
            return
        }
        if (type == 1 && that.data.picList.length > 19) {
            wx.$Toast("最多上传20张照片");
            return
        }
        that.identity(type)
    },
    upimg(tempFilePath, type, self) {
        wx.uploadFile({
            url: wx.$config.upload,
            filePath: tempFilePath,
            name: 'file',
            formData: {
                token: wx.getStorageSync('token')
            },
            success: res => {
                let data = typeof res.data == "string" ? JSON.parse(res.data) : null
                if (type == 0) {
                    console.log(self.data.imgList)
                    let imgArr, idArr, imgSrcArr;
                    if (self.data.imgList.length > 0) {
                        imgArr = self.data.imgList,
                            idArr = self.data.collection,
                            imgSrcArr = self.data.imgSrcArr;
                    } else {
                        imgArr = [];
                        idArr = [];
                        imgSrcArr = []
                    }
                    imgArr.push(data.data);
                    idArr.push(data.data.resource_id);
                    imgSrcArr.push(data.data.resource_href);
                    self.setData({
                        imgList: imgArr,
                        collection: idArr,
                        imgSrcArr: imgSrcArr
                    })
                } else if (type == 1) {
                    let picArr, idArr, picSrcArr;
                    if (self.data.picList.length > 0) {
                        picArr = self.data.picList,
                            idArr = self.data.contract,
                            picSrcArr = self.data.picSrcArr
                    } else {
                        picArr = [];
                        idArr = [];
                        picSrcArr = []
                    }
                    picArr.push(data.data);
                    idArr.push(data.data.resource_id);
                    picSrcArr.push(data.data.resource_href);
                    self.setData({
                        picList: picArr,
                        contract: idArr,
                        picSrcArr: picSrcArr
                    })
                }
            }
        })

    },
    delImg(e) {
        let {
            index,
            type
        } = e.currentTarget.dataset, that = this, imgArr;
        if (type == 0) {
            imgArr = that.data.imgList;
            imgArr.splice(index, 1);
            that.setData({
                imgList: imgArr
            })
        } else {
            imgArr = that.data.picList
            imgArr.splice(index, 1);
            that.setData({
                picList: imgArr
            })
        };
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})